<?php
use lib\controller\Controller;
use lib\dao\query\Query;
use lib\dao\query\QueryLimit;
use lib\image\SimpleImage;
use lib\dao\query\QueryLike;
use lib\dao\query\QueryAnd;
use lib\factory\Factory;
use lib\factory\FactoryModel;

class EventoController extends Controller{

/********************** FRONTEND **************************/
	public function index(){
            try{
                $this->getMessages();
                $search = $this->getParam('search');
                $categoria_id = $this->getParam('categoria_id');
                $this->View->layout = 'frontend';

            //Validamos que la categoria exista
                if(empty($categoria_id)){
                    $this->_helper->flashMessenger->addMessage('error');
                    $this->_helper->flashMessenger->addMessage('No es posible continuar sin identificador');
                    $this->_redirect("/categoria/", array('exit'=>true));
                }
            
            //Obtenemos la lista de eventos para la categoria
                $Q = new Query($this->Model);
                $Q->add(new QueryAnd('categoria_id',$categoria_id));
                if($search){
                    $Q->add(new QueryLike('nombre',$search));
                }
                $eventos=$this->Model->eventoActivo($Q);
            
            //Filtro de busqueda de eventos
                if(empty($eventos) && empty($search)){
                    $this->_helper->flashMessenger->addMessage('error');
                    $this->_helper->flashMessenger->addMessage('No hay eventos para la categoria');
                    $this->_redirect("/categoria/", array('exit'=>true));
                }
            
            //Asginamos valores a la vista
                $this->View->assign('rows',$eventos);
                $this->View->assign('categoria',$categoria_id);
                $this->View->assign('search', $search);
                
            }catch (\Exception $e){
                $this->View->assign('msg', array('error',$e->getMessage()));
            }
            $this->View->display();
                
	}

	public function detalle(){
		try{
			$this->View->layout = 'frontend';
			$id = $this->getParam('id');
			if(empty($id)){
				throw new \Exception('No es posible continuar sin identificador');
			}
		//Levanto la info del evento
			$Q = new Query($this->Model);
			$Q->add(new QueryAnd('e.id',$id));
			$evento = $this->Model->detalleEvento($Q);

			if(empty($evento)){
				throw new \Exception('No exite evento para ese identificador');
			}
			$this->View->assign('evento', $evento);
		
		//Levanto la cantidad de entradas vendidas
			$QE = new Query($this->Model);
			$QE->add(new QueryAnd('evento_id',$id));
			$this->View->assign('entradasVendidas', $this->Model->entradasXEvento($QE));

		//Levantamos el detalle de cada sector 
			$QS = new Query($this->Model);
			$QS->add(new QueryAnd('evento_id',$id));
			$this->View->assign('detalleSectores', $this->Model->detalleXSector($QS));			

		}catch (\Exception $e){
			$this->View->assign('msg', array('error',$e->getMessage()));
		}
		$this->View->display();
	}

/***************** BACKEND ********************/
	public function listado(){
		try{
			//$this->View->debug();
			$this->getMessages();
                        $search = $this->getParam('search');
                        $categoria = $this->getParam('categoria');
                        
                        $Q = new Query($this->Model);
                        if($search){
				$Q->add(new QueryLike('nombre',$search));
				//con un objeto
				/*
				$Q->add(new QueryLike(array('nombre'=>$this->getParam($search),
				'descripcion'=>$this->getParam('search'))));
				*/
			}	
			if($categoria){
				$Q->add(new QueryAnd('categoriaId',$categoria));
				$Categoria = Factory::create(FactoryModel::getInstance(), 'Categoria');
				$Q2 = new Query($Categoria);
				$Q2->add(new QueryAnd('id',$categoria));
				$Categoria->load($Q2);
				$this->View->assign('categoria', $Categoria->toArray());
			}
                        
                        //Asigno resultado a la vista
			$this->View->assign('rows', $this->Model->fetch());
			
			//creo un modelo de categoria
			$CategoriaE = Factory::create(FactoryModel::getInstance(), 'Categoria');
			$this->View->assign('categorias', $this->model2List($CategoriaE->fetch(),'id','nombre'));

			//creo un modelo de lugares
			$Lugares = Factory::create(FactoryModel::getInstance(), 'Lugar');
			$this->View->assign('lugares', $this->model2List($Lugares->fetch(),'id','nombre'));
			
			
			$P = new QueryLimit($this->getPage(),(int)$this->Config->pagination->rows);
			$Q->add($P);
			
			$Q->prepare($this->Model);	
			//$Q->dump();
			$this->View->assign('rows', $this->Model->fetch($Q));
			$this->View->assign('P', $P);
			$this->View->assign('page', $this->getPage());
			$this->View->assign('search', $search);
			//Muestro template
			$this->View->display();
                        
                        
		}
		catch (\Exception $e){
			die($e->getMessage());
		}		
	}
	
	

	
	public function crear(){
		try{
			//hidden o tomar valor del boton submit para saber si
			//postearon formulario.
			$do_submit = $this->getParam('do_submit');
			
			//creo un modelo de categoria
			$Categoria = Factory::create(FactoryModel::getInstance(), 'Categoria');
			$this->View->assign('categorias', $this->model2List($Categoria->fetch(),'id','nombre'));
				
			//creo un modelo de lugares
			$Lugares = Factory::create(FactoryModel::getInstance(), 'Lugar');
			$this->View->assign('lugares', $this->model2List($Lugares->fetch(),'id','nombre'));
			
			if($do_submit){
				
				$this->params2Model($this->Model,array('imagen'));
                                $this->required($this->Model, array('nombre'));
				$this->Model->token = $this->_helper->Token(20);
				$this->Model->create();
				if($_FILES['imagen']['error'] == UPLOAD_ERR_OK){
					$tmp_name = $_FILES["imagen"]["tmp_name"];
					$name = $_FILES["imagen"]["name"];
					$extension = substr($name, strripos($name, '.'));
					$name = $this->Model->id.$extension;
					move_uploaded_file($tmp_name, $this->Config->image->uploads->path.$name);
                                        $this->Model->imagen = $name;
                                        $this->Model->update();
					
					$image = new SimpleImage($this->Config->image->uploads->path.$name);
					$image->square($this->Config->image->square);
					$image->save($this->Config->image->uploads->mini.$name);
                                        
				}else{
                                        $name = "nofoto.jpg";
                                        $this->Model->imagen = $name;
                                        $this->Model->update();
                                }
				$this->clean($this->Model);
				$this->View->assign('msg', array('success', $this->Tr->_('saved_ok')));
                                
			}
		}
		catch (\Exception $e){
			$this->View->assign('msg', array('error',$e->getMessage()));
		}
		$this->View->assign('model', $this->Model->toArray());
		$this->View->display();	
	}
	
	public function eliminar(){		
			$id = $this->getParam('id');	
                        $Q= new Query($this->Model);
			$Q->add(new QueryAnd('id',$id));
			
                        if(empty($id)){
				
                                header("location:/evento/index/status/1/");
				exit();
			}
				
			$this->Model->id = $id;
			if(!$this->Model->load($Q)){
                                
				header("location:/evento/index/status/2/");
				exit();
			}
			
			$this->Model->delete();
                        
			header("location:/evento/index/status/0/");
			exit();		
	}
	
	public function actualizar(){
		try{
			//hidden o tomar valor del boton submit para saber si
			//postearon formulario.
			$do_submit 	= $this->getParam('do_submit');
			$id 		= $this->getParam('id');
			
			if(empty($id)){
				throw new \Exception('No es posible continuar sin identificador');
			}
			
			$this->Model->id = $id;
                        
                        $Q= new Query($this->Model);
			$Q->add(new QueryAnd('id',$id));
                        
			if(!$this->Model->load($Q)){
				throw new \Exception('Identificador no valido');
			}
			
			//creo un modelo de categoria
			$Categoria = Factory::create(FactoryModel::getInstance(), 'Categoria');
			$this->View->assign('categorias', $this->model2List($Categoria->fetch(),'id','nombre'));
				
			//creo un modelo de lugares
			$Lugares = Factory::create(FactoryModel::getInstance(), 'Lugar');
			$this->View->assign('lugares', $this->model2List($Lugares->fetch(),'id','nombre'));
			
			
			if($do_submit){
				//cargo modelo con parametros del form
				
                                $this->params2Model($this->Model, array('imagen'));
				
				if($_FILES['imagen']['error'] == UPLOAD_ERR_OK){
					$tmp_name = $_FILES["imagen"]["tmp_name"];
					$name = $_FILES["imagen"]["name"];
					$extension = substr($name, strripos($name, '.'));
					$name = $this->Model->id.$extension;
					move_uploaded_file($tmp_name, $this->Config->image->uploads->path.$name);
					$this->Model->imagen = $name;
					$this->Model->update();						
					$image = new SimpleImage($this->Config->image->uploads->path.$name);
						
					
					$image->square($this->Config->image->square);
					$image->save($this->Config->image->uploads->mini.$name);
				}
				//campos obligatorios
				$this->required($this->Model, array('nombre'));
				//invoco update heredado de Model
				$this->Model->update();
                                
				$this->View->assign('msg', array('success', 'El registro se ha actualizado correctamente'));
			}
		}
		catch (\Exception $e){
			$this->View->assign('msg', array('error',$e->getMessage()));
		}
		$this->View->assign('id', $id);
		$this->View->assign('model', $this->Model->toArray());
		$this->View->display();
	}
}